using JT808Protocol.Abstracts;
using JT808Protocol.Methods;
using JT808Protocol.Models;
using SuperSocket.ProtoBase;
using System.Buffers;

namespace JT808Gateway.Core
{
    public class JT808PackageFilter : BeginEndMarkPipelineFilter<JT808Package>
    {
        private IJT808Parser _serializer = new JT808Parser();

        /// <summary>
        /// 部标数据包头尾标识
        /// </summary>
        private static byte[] _beginEndFlag => new byte[] { 0x7E };

        private bool _foundBeginMark = false;

        public JT808PackageFilter()
            : base(_beginEndFlag, _beginEndFlag)
        { }

        public override JT808Package Filter(ref SequenceReader<byte> reader)
        {
            var sequence = reader.Sequence;

            if (!_foundBeginMark)
            {
                if (!reader.IsNext(_beginEndFlag[0], advancePast: true))
                {
                    throw new ProtocolException("Invalid beginning part of the package.");
                }

                _foundBeginMark = true;
            }

            if (!reader.TryAdvanceTo(_beginEndFlag[0]))
            {
                return null;
            }

            return DecodePackage(ref sequence);
        }

        protected override JT808Package DecodePackage(ref ReadOnlySequence<byte> buffer)
        {
            var package = _serializer?.Parse(buffer.FirstSpan);

            _foundBeginMark = false; // reset

            return package;
        }
    }
}